import { createRouter, createWebHistory } from "vue-router";

const routes = [
  {
    path: "/",
    redirect: "/index/home",
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../components/Login.vue"),
  },
  {
    path: "/home",
    name: "Home",
    component: () => import("../components/Home.vue"),
    children: [
      {
        path: "category",
        name: "Category",
        component: () => import("../components/Category.vue"),
      },
      {
        path: "book",
        name: "Book",
        component: () => import("../components/Book.vue"),
      },
      {
        path: "book_add",
        name: "BookAdd",
        component: () => import("../components/BookAdd.vue"),
      },
      {
        path: "record",
        name: "Records",
        component: () => import("../components/Records.vue"),
      },
      {
        path: "carousel",
        name: "Carousel",
        component: () => import("../components/CarouselMan.vue"),
      },
      {
        path: "caution",
        name: "Caution",
        component: () => import("../components/Caution.vue"),
      },{
        path: "user",
        name: "User",
        component: () => import("../components/User.vue"),
      }
    ],
  },
  {
    path: "/index",
    name: "Index",
    component: () => import("../front/Index.vue"),
    children: [
      {
        path: "home",
        name: "DefaultHome",
        component: () => import("../front/DefaultHome.vue"),
      },
      {
        path: "book",
        name: "FrontBooks",
        component: () => import("../front/FrontBooks.vue"),
      },
      {
        path: "detail/:bookId.html",
        name: "BookDetail",
        component: () => import("../front/BookDetail.vue"),
        props: true,
      },
      {
        path: "profile",
        name: "Profile",
        component: () => import("../front/Profile.vue"),
        children: [
          {
            path: "record",
            name: "RecordBorrow",
            component: () => import("../front/RecordBorrow.vue"),
          },
          {
            path: "repass",
            name: "Repassword",
            component: () => import("../front/Repassword.vue"),
          }
        ]
      },
    ],
  },
];

const router = createRouter({
  routes,
  history: createWebHistory(),
});

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem("token");
  if (to.fullPath == "/login" || to.fullPath == "/index") {
    next();
  } else {
    if (token != null && token != "") {
      next();
    } else {
      next("/login");
    }
  }
});

// router.beforeEach((to, from, next) => {
//   let loginToken = localStorage.getItem("token");
//   //console.log(loginToken);
//   if (to.path == '/login' || to.path =='/index' ||   to.path =='/index/book') {
//     next()
//   } else {
//     if (loginToken != null && loginToken != '') {
//       next()
//     } else {
//       next('/login')
//     }
//   }
// });

export default router;
